/**
 * @desc
 *
 * @使用场景
 *
 * @author  杨晓东[of1081]
 * @company qianmi.com
 * @Date    16/10/22
 **/
var fs =require('fs');
var fse = require("fs-extra");
var path  =require('path');
// var urllib = require('urllib');
var request  =require('request');
var childProcess=require('child_process');

import {NpmPackageInfo,NpmPackageDownLoadInfo} from './npm-package-info';
//tar zxvf template-files-0.0.2.tgz template-files


/**
 * 获取Npm包最新版本信息,
 * @param npmPackageDownLoadInfo
 */
export async function getNpmVersionInfo (npmPackageInfo:NpmPackageInfo) {

}

/**
 * 从NPM服务器下载相应的包,并且解压到指定目录去.
 *  如果本地有.此版本, 则不需要再加载 了...
 * @param npmPackageDownLoadInfo
 * @return {{npmPackageDir: string}}
 */
export async function loadNpmPackage (npmPackageDownLoadInfo:NpmPackageDownLoadInfo) {
    let {distDir,version,name}=npmPackageDownLoadInfo;
    let npmPackageDir =path.join(distDir,name);
    let _tplNpmPackage= {version:""};
    try{
        console.log('读取本地模板版本:',path.join(npmPackageDir,'package.json'));
        _tplNpmPackage = fse.readJSONSync(path.join(npmPackageDir,'package.json'));
    }catch(err){
    }

    if( _tplNpmPackage.version === version){
        console.log('本地已经有此版本了.. 不再加载 ',version,name);
        return {npmPackageDir};
    } else {
        console.log('重新加载版本了..',version,name);
    }

    let _loadUrl  =`http://registry.npm.qianmi.com/${name}/download/${name}-${version}.tgz`;
    let _distPwd =path.join(distDir,`${name}-${version}.tgz`);
    fse.ensureFileSync(_distPwd);
    //下载npm包
    await _loadNpmTar({fileUrl:_loadUrl,distPath:_distPwd});
    //解压文件;;
    // await sleep(5000);
    let _fulPath  =path.join(distDir,`${name}-${version}.tgz`); //`${name}-${version}.tgz`,'..'
    let _workBench = path.join(_fulPath,'..');
    let __ =_fulPath.split(path.sep);
    let _fileName  =__[__.length-1];
    console.log('解压文件::',_fileName);
    let _out = childProcess.execSync(`pwd && tar zxvf ${_fileName}`, {
        cwd: _workBench,
        timeout: 50000
    });


    console.log('删除文件压缩包::',_fileName);
    fse.remove(path.join(distDir, `${name}-${version}.tgz`), function (err) {
        if (err) return console.error(err);
        console.log('success!');
    });

    //重命名.
    console.log('重名命文件::',_fileName);
    await _renameFile(path.join(_workBench,'package'),npmPackageDir,{clobber:true});
    // fse.move(,(err)=>{
    //     if (err) return console.error(err);
    //     console.log('success!');
    // });
    console.log(_out.toString());
    return {npmPackageDir}
}

async function _renameFile(src,dest,options){

    return new Promise((resolve,reject)=>{
        fse.move(src,dest,options,(err)=>{
            if (err){
                console.error(err);
                reject();
            }else{
                resolve()
            }
        });
    });
}
 async function _loadNpmTar({fileUrl,distPath}){

     return new Promise((resolve,reject)=>{
         request(fileUrl)
             .pipe(fs.createWriteStream(distPath))
             .on('finish', () => {
                 resolve();
                 console.error('All writes are now complete.');
             })
             .on('error',(error)=>{
                 reject(error);
             });
     });
}

function sleep(ms){
    return new Promise((resolve,reject)=>{
        setTimeout(resolve,ms);
    });
}

